<?php

namespace app\common\model\product;

use app\api\model\supplier\Supplier as SupplierModel;
use app\common\library\helper;
use app\common\model\BaseModel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 商品模型
 */
class Car extends BaseModel
{
    protected $name = 'car';

    /**
     * 获取商品列表
     */
    public static function getAll()
    {
        $model = new static;
//        if (!Cache::get('car_' . $model::$app_id)) {
            $data = $model->select();
            $all = !empty($data) ? $data->toArray() : [];
            $tree_data = self::buildTree($all);
            Cache::tag('cache')->set('car_' . $model::$app_id, compact('tree_data'));
//        }
        return Cache::get('car_' . $model::$app_id);
    }

    /**
     * 构建树形结构
     *
     * @param array $items 原始数据数组
     * @param int $parentId 父级ID
     * @return array 树形结构
     */
    private static function buildTree(array $items, int $parentId = 0): array
    {
        $branch = [];

        foreach ($items as $item) {
            if ($item['parentid'] == $parentId) {
                $children = self::buildTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $branch[] = $item;
            }
        }

        return $branch;
    }
}
